import java.util.concurrent.*;

public class Main {
    /*
    * 这个代码主要演示的是两个线程池来共享一个阻塞队列,
    * 核心的思想就是:将阻塞队列作为全局变量，然后两个线程池去使用这个
    * */
    public static void main(String[] args) {
        /*创建一个阻塞队列，这里的阻塞队列作为全局变量*/
        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
        /*创建推动消息的线程池，将任务提交到阻塞队列里面*/
        ExecutorService pushThreadPool = Executors.newFixedThreadPool(1);
        pushThreadPool.submit(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    final int taskId=i;
                    queue.put(() -> {
                        System.out.println("task"+taskId+"is pushed");
                    });
                    Thread.sleep(1000);/*模拟推送的延迟*/
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        /*创建拉取消息的线程池，从阻塞队列里面获取任务并执行*/
        ThreadPoolExecutor pullThreadPool = new ThreadPoolExecutor(2, 2, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
        for (int i = 0; i < 2; i++) {
            pullThreadPool.execute(() -> {
                try {
                    while (true){
                        Runnable task=queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        /*关闭线程池*/
        pushThreadPool.shutdown();
        pullThreadPool.shutdown();
    }
}